import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:custom_refresh_indicator/custom_refresh_indicator.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:insta_image_viewer/insta_image_viewer.dart';
import 'package:school_assistant/user_feedback_imgs.dart';
import 'package:sp_util/sp_util.dart';

import 'article_detail.dart';
import 'common_client.dart';
import 'common_colors.dart';
import 'data/article_entity.dart';
import 'data/article_extra_entity.dart';

class MyActicle extends StatefulWidget {
  const MyActicle({Key? key}) : super(key: key);

  @override
  State<MyActicle> createState() => _MyActicleState();
}

class _MyActicleState extends State<MyActicle> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: CommonColor.colorF5,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        title: Text(
          "我的帖子",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
      ),
      body: CustomRefreshIndicator(
        child: ListView.builder(
          itemBuilder: (cxt, index) {
            return _item(index);
          },
          itemCount: articles.length,
        ),
        builder: MaterialIndicatorDelegate(
          builder: (context, controller) {
            return Icon(
              Icons.ac_unit,
              color: Colors.blue,
              size: 30,
            );
          },
        ),
        onRefresh: myAsyncRefreshFunction,
      ),
    );
  }

  Future<void> myAsyncRefreshFunction() async {
    _getArticle();
  }

  @override
  void initState() {
    super.initState();
    _getArticle();
  }

  _item(int index) {
    var articleEntity = articles[index];
    ArticleExtraEntity? extra;
    List<dynamic> imgs = jsonDecode(articleEntity.image ?? '');
    if (articleEntity.extra?.isNotEmpty == true) {
      extra =
          ArticleExtraEntity.fromJson(jsonDecode(articleEntity.extra ?? ''));
    }
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(left: 12, right: 12, top: 12),
        padding: EdgeInsets.all(12),
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(4)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              children: [
                CachedNetworkImage(
                    imageBuilder: (context, image) => CircleAvatar(
                          backgroundImage: image,
                        ),
                    errorWidget: (context, url, error) => CircleAvatar(
                          backgroundImage:
                              AssetImage(UserFeedBackImgs.user_male),
                        ),
                    width: 50,
                    height: 50,
                    imageUrl: UserFeedBackImgs.url + (extra?.profile ?? '')),
                SizedBox(
                  width: 12,
                ),
                RichText(
                    text: TextSpan(children: [
                  TextSpan(
                      text: (extra?.username ?? "姓名") + "\n",
                      style: TextStyle(
                          color: Color(0XFF333333), fontSize: 13, height: 2)),
                  TextSpan(
                      text: extra?.time ?? "2202-10-11",
                      style: TextStyle(
                          color: Color(0XFF333333), height: 2, fontSize: 13))
                ]))
              ],
            ),
            Container(
              padding: EdgeInsets.all(6),
              margin: EdgeInsets.only(top: 6),
              decoration: BoxDecoration(
                  color: Color(0XFFF1F1F1),
                  borderRadius: BorderRadius.circular(4)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(articleEntity.title ?? "",
                      style: TextStyle(
                          color: Color(0XFF333333),
                          fontSize: 15,
                          fontWeight: FontWeight.w600)),
                  SizedBox(
                    height: 4,
                  ),
                  Text(articleEntity.body ?? "",
                      style: TextStyle(
                        color: Color(0XFF666666),
                        fontSize: 14,
                      )),
                  SizedBox(
                    height: 4,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: 1,
                      crossAxisSpacing: 10,
                    ),
                    itemCount: imgs.length,
                    itemBuilder: (context, index) {
                      //   return Image.file(File(imgAD[index].path));
                      return _singleAD(UserFeedBackImgs.url + imgs[index]);
                    },
                  ),
                  SizedBox(
                    height: 10,
                  ),
                ],
              ),
            )
          ],
        ),
      ),
      onTap: () {
        Get.to(ArticleDetail(articleEntity));
      },
    );
  }

  _singleAD(String pos) {
    return InstaImageViewer(
      child: CachedNetworkImage(
        width: 68,
        height: 68,
        fit: BoxFit.cover,
        alignment: Alignment.topCenter,
        imageUrl: pos,
      ),
    );
  }

  List<ArticleEntity> articles = [];

  _getArticle() async {
    try {
      var res = await CommonClient()
          .getArticle(1, 100, user: SpUtil.getString("uid"));
      List<dynamic> data = jsonDecode(res.data ?? "");
      List<ArticleEntity> gs = [];
      if (data != null) {
        data.forEach((element) {
          gs.add(ArticleEntity.fromJson(element));
        });
      }
      setState(() {
        articles.clear();
        articles.addAll(gs);
      });
      print(gs);
    } catch (e) {
      print(e);
    }
  }
}
